package com.gupao.spring.servlet;

import com.gupao.spring.servlet.annotation.GPAutowired;
import com.gupao.spring.servlet.annotation.GPController;
import com.gupao.spring.servlet.annotation.GPService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Service;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class DispatchServlet extends HttpServlet {

    private Properties contextConfig = new Properties();

    private Map<String,Object> beanMap = new ConcurrentHashMap<String, Object>();

    private List<String> classNames = new ArrayList<String>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("--------调用post方法--------");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //开始初始化的进程

        //定位
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        //加载
        doScanner(contextConfig.getProperty("scanPackage"));
        //注册
        doRegistry();

        //自动依赖注入
        //这一步Spring是调用getBean方法才会触发的
        doAutowired();

        //如果是SpringMVC，则会多设计一个handerMapping
        //@RequestMapping配置的url和Method关联上
        //以便于从浏览器获取用户输入的url,找到具体执行的Method，通过反射去调用
        initHanderMapping();

    }

    private void initHanderMapping() {
    }

    private void doAutowired() {
        if(beanMap.isEmpty()){
            return;
        }
        for (Map.Entry<String,Object> entry : beanMap.entrySet()){
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields){
                if(!field.isAnnotationPresent(GPAutowired.class)){
                    continue;
                }
                GPAutowired autowired = field.getAnnotation(GPAutowired.class);
                String beanName = autowired.value();
                if("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                field.setAccessible(true);

                try {
                    //field.set()第一个参数为该字段所在的对象，第二个为真正的值，即字段的值
                    field.set(entry.getValue(),beanMap.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doRegistry() {
        if(classNames.isEmpty()){
            return;
        }
        for (String className : classNames){
            try {
                Class<?> clazz = Class.forName(className);
                //这里在Spring中是用多个子方法处理的，策略模式
                if(clazz.isAnnotationPresent(GPController.class)){
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();
                    //Spring中put的不是instance实例，而是BeanDefinition
                    beanMap.put(beanName,instance);
                }else if(clazz.isAnnotationPresent(GPService.class)){
                    GPService service = clazz.getAnnotation(GPService.class);
                    //默认用类名首字母注入
                    //如果自己在GPService注解定义了beanName,优先使用beanName
                    //如果是一个接口，使用接口的类型去自动注入


                    //在Spring中同样会调用不同的方法，autowiredByName autowiredByType
                    String beanName = service.value();
                    if("".equals(beanName.trim())){
                        beanName = clazz.getSimpleName();
                    }
                    Object instance = clazz.newInstance();
                    beanMap.put(beanName,instance);

                    Class<?>[] interfaces = clazz.getInterfaces();

                    for (Class<?> i: interfaces){
                        beanMap.put(i.getName(),instance);
                    }
                }else {
                    continue;
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    private void doScanner(String packageName) {
        URL url = this.getClass().getResource("/" + packageName.replaceAll("\\.","/"));
        File classDir = new File(url.getFile());
        for (File file : classDir.listFiles()){
            //递归查找所有的类
            if(file.isDirectory()){
                doScanner(packageName + "." + file.getName());
            }else {
                classNames.add(packageName + "." + file.getName().replace(".class",""));
            }
        }
    }

    private void doLoadConfig(String location) {
//        System.out.println("==="+location);
        //spring中是通过Reader去查找和定位
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(location.replace("classpath:",""));
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private String lowerFirstCase(String str){
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }
}
